import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:lyps_music/components/home_control.dart';
import 'package:lyps_music/request/api.dart';
import 'package:lyps_music/store/index.dart';
import 'package:provider/provider.dart';

/// 自动补全搜索框
class SearchInput extends StatefulWidget {
  const SearchInput({super.key});

  @override
  State<StatefulWidget> createState() => _SearchInputState();
}

class _SearchInputState extends State<SearchInput> {
  final FocusNode focusNode = FocusNode();
  final LayerLink _layerLink = LayerLink();
  String searchText = "";
  List<dynamic> wordList = [];
  Timer? timer;
  final TextEditingController editController = TextEditingController();

  OverlayEntry? listSuggestionsEntry;

  @override
  void initState() {
    super.initState();
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (searchText != "") {
          _updateOverlay();
        }
      } else {
        Future.delayed(const Duration(milliseconds: 200), () {
          _updateOverlay(true);
        });
      }
    });
  }

  void _updateOverlay([bool remove = false]) {
    if (remove) {
        listSuggestionsEntry?.remove();
        listSuggestionsEntry = null;
        return;
      }
    if (listSuggestionsEntry == null) {
      final Size textFieldSize = (context.findRenderObject() as RenderBox).size;
      final width = textFieldSize.width;
      final height = textFieldSize.height;
      listSuggestionsEntry = OverlayEntry(
        builder: (context) {
          return Positioned(
            width: width,
            child: CompositedTransformFollower(
              link: _layerLink,
              showWhenUnlinked: false,
              offset: Offset(0, height),
              child: Card(
                child: Container(
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), color: Colors.white),
                  child: _showWordList(),
                ),
              ),
            ),
          );
        },
      );
      Overlay.of(context).insert(listSuggestionsEntry!);
    }
    listSuggestionsEntry!.markNeedsBuild();
    
  }

  Future<void> _searchWordList() async {
    var res = await Api.getWordList(searchText);
    setState(() {
      wordList = res.data['data'];
    });
  }

  Future<void> _searchMusicList() async {
    var res = await Api.searchList(searchText);
    // ignore: use_build_context_synchronously
    context.read<Store>().musicList = res.data['data']['list'];
  }

  Widget _showWordList() {
    if (wordList.isEmpty) {
      return Text("暂无数据");
    } else {
      return Column(
        children: wordList.map((item) {
          return MouseRegion(
            cursor: SystemMouseCursors.click,
            child: InkWell(
              onTap: () {
                editController.text = item['name'];
                searchText = item['name'];
                _searchMusicList();
                focusNode.unfocus();
              },
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey))),
                child: Text(
                  item['name'],
                  style: TextStyle(fontSize: 12),
                ),
              ),
            ),
          );
        }).toList(),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: TextField(
        controller: editController,
        style: TextStyle(fontSize: 14, height: 1, color: Colors.white),
        focusNode: focusNode,
        decoration: InputDecoration(
          // isCollapsed: true,
          hintText: "请输入关键词",
          hintStyle: TextStyle(color: Colors.white.withOpacity(0.5)),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: Colors.transparent)),
          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: Colors.transparent)),
          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: Colors.transparent)),
        ),
        onChanged: (value) {
          searchText = value;
          if (timer != null) timer?.cancel();
          if (value != "") {
            timer = Timer(const Duration(seconds: 1), () async {
              await _searchWordList();
              _updateOverlay();
            });
          }
        },
        onSubmitted: (value) {
          searchText = value;
          _searchMusicList();
        },
      ),
    );
  }
}
